/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ui.views;

import com.vaadin.data.Buffered.SourceException;
import com.vaadin.data.Item;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Component;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.FormFieldFactory;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Window;
import java.util.Arrays;
import org.jboss.weld.util.collections.Arrays2;
import ui.controllers.RegistrationController;

/**
 *
 * @author Spyros
 */
public class RegistrationView {

    private Panel mainPanel;
    private RegistrationController controller;

    public RegistrationView() {
        controller = new RegistrationController();
    }

    public Component init() {
        initializeComponents();
        return mainPanel;
    }

    private void initializeComponents() {
        mainPanel = new Panel();
        final Form registrationForm = new Form();
        final FormFieldFactory oldFieldFactory = registrationForm.getFormFieldFactory();
        registrationForm.setFormFieldFactory(new FormFieldFactory() {

            @Override
            public Field createField(Item item, Object propertyId, Component uiContext) {
                Field f = oldFieldFactory.createField(item, propertyId, uiContext);
                ((TextField)f).setNullRepresentation("");
                f.setRequired(true);
                return f;
            }
        });
        registrationForm.setItemDataSource(controller.getUserDataSource());
        registrationForm.setVisibleItemProperties(Arrays.asList(new String[]{"username", "password", "email"}));
        mainPanel.addComponent(registrationForm);
        Button submitButton = new Button("Υποβολή");
        submitButton.addListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                try {
                    registrationForm.commit();
                    controller.register(registrationForm.getItemDataSource());
                    Window mainWindow = mainPanel.getWindow();
                    mainWindow.removeAllComponents();
                    LoginView loginView = new LoginView();
                    mainWindow.addComponent(loginView.init());
                    mainWindow.showNotification("Η εγγραφή σας ολοκληρώθηκε");
                } catch (SourceException sourceException) {
                } catch (InvalidValueException invalidValueException) {
                }
            }
        });
        mainPanel.addComponent(submitButton);
    }
}
